#include "dspSimulator/irGenerator/irGenerator.h"
#include "simulator/report/report.h"

void IRGenerator::init(std::shared_ptr<LLVMJit> llvmJit) {
    m_llvmContext = llvmJit->getLLVMContext();
    m_llvmModule = llvmJit->getCurModulePtr();
    m_irBuilder = llvmJit->getIrBuilder();
}

llvm::Value *IRGenerator::getGlobalValue(const std::string &name) {
    if (m_llvmModule == nullptr) {
        fatalMacro("当前IR生成器的llvm模块为空！");
    }
    auto globalValuePtr = m_llvmModule->getNamedGlobal(name);
    return m_irBuilder->CreateLoad(globalValuePtr);
}

llvm::Value *IRGenerator::createGlobalValue(const std::string &name, llvm::Type *type) {
    if (m_llvmModule == nullptr) {
        fatalMacro("当前IR生成器的llvm模块为空！");
    }
    return m_llvmModule->getOrInsertGlobal(name, type);
}


llvm::LLVMContext *IRGenerator::getLLVMContext() {
    return m_llvmContext;
}

llvm::Module *IRGenerator::getLLVMModule() {
    return m_llvmModule;
}

std::shared_ptr<llvm::IRBuilder<>> IRGenerator::getLLVMIRBuilder() {
    return m_irBuilder;
}

llvm::Function *
IRGenerator::createFunctionWithExternalLinkage(llvm::FunctionType *functionType, const std::string &funcName) {
    if (m_llvmModule == nullptr) {
        fatalMacro("当前IR生成器的llvm模块为空！");
    }
    return llvm::Function::Create(functionType, llvm::GlobalValue::ExternalLinkage, funcName, m_llvmModule);
}
